<!--
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-12-06 16:57:41
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2024-09-14 14:20:18
-->
<template>
  <div>
    <el-dialog
      title="新增单位"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refForm"
        label-width="110px"
      >
        <el-row>
          <el-col>
            <el-form-item size="small" label="单位名称" prop="orgName">
              <el-input
                clearable
                v-model.trim="addForm.orgName"
                placeholder="请输入名称"
                style="width: 100%"
                oninput="value=value.replace(/\s*/g,'')"
                @blur="addForm.orgName = $event.target.value"
                maxlength="20"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item size="small" label="所属国家" prop="homeCountry">
              <el-select clearable filterable v-model='addForm.homeCountry' style="width: 100%;" placeholder='请选择所属国家'>
                <el-option v-for='item in homeCountryList' :label='item.value' :value='item.value' :key='item.value'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="单位监管类型" prop="flatType">
              <el-select
                clearable
                v-model="addForm.flatType"
                style="width: 100%"
                placeholder="请选择单位监管类型"
              >
                <el-option
                  v-for="item in flatTypeList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="单位性质" prop="nature">
              <el-select
                clearable
                v-model="addForm.nature"
                style="width: 100%"
                placeholder="请选择单位性质"
              >
                <el-option
                  v-for="item in natureList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="单位类别" prop="category">
              <el-select
                clearable
                v-model="addForm.category"
                style="width: 100%"
                placeholder="请选择单位类别"
              >
                <el-option
                  v-for="item in categoryList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="监管等级" prop="grade">
              <el-select
                clearable
                v-model="addForm.grade"
                style="width: 100%"
                placeholder="请选择监管等级"
              >
                <el-option
                  v-for="item in gradeList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item size="small" label="地区" prop="streetCode">
          <div style="display: flex; align-items: center">
            <!-- <el-input v-model.trim="addForm.province" disabled placeholder="省"></el-input>
                  <el-input v-model.trim="addForm.city" disabled placeholder="市"></el-input>
                  <el-input v-model.trim="addForm.area" disabled placeholder="区"></el-input>
                  <el-input v-model.trim="addForm.street" disabled placeholder="街道"></el-input> -->

            <el-select
              v-model="addForm.provinceCode"
              placeholder="省"
              @change="changprovince"
              style="width: 400px"
            >
              <el-option
                v-for="(item, i) in provinceList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addForm.cityCode"
              placeholder="市"
              @change="changcity"
              style="width: 400px"
            >
              <el-option
                v-for="(item, i) in cityList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addForm.areaCode"
              placeholder="区"
              @change="changarea"
              style="width: 400px"
            >
              <el-option
                v-for="(item, i) in areaList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addForm.streetCode"
              placeholder="街道"
              @change="changestreet"
              style="width: 400px"
            >
              <el-option
                v-for="(item, i) in streetList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>

            <i
              class="iconfont zuobiao"
              style="font-size: 20px; margin-left: 10px; cursor: pointer"
              @click="openMap"
            ></i>
          </div>
        </el-form-item>

        <el-form-item size="small" label="详细地址" prop="address">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="详细地址"
            v-model="addForm.address"
            oninput="value=value.replace(/\s*/g,'')"
            @blur="addForm.address = $event.target.value"
            maxlength="30"
            resize="none"
            :autosize="{ minRows: 2, maxRows: 5 }"
          >
          </el-input>
        </el-form-item>

        <el-form-item size="small" label="社区">
          <el-select
            v-model="addForm.communityCode"
            clearable
            @change="changecommunity"
            style="width: 100%"
            placeholder="请选择社区"
          >
            <el-option
              v-for="(item, i) in communityList"
              :key="i"
              :label="item.regionName"
              :value="item.regionCode"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="值班室电话" prop="telephone">
              <el-input
                oninput="value=value.replace(/[^\d]/g,'')"
                @blur="addForm.telephone = $event.target.value"
                clearable
                placeholder="请输入值班室电话"
                maxlength="11"
                v-model.trim="addForm.telephone"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="施工单位" prop="construction">
              <el-input
                oninput="value=value.replace(/\s*/g,'')"
                @blur="addForm.construction = $event.target.value"
                clearable
                placeholder="请输入施工单位"
                maxlength="20"
                v-model.trim="addForm.construction"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="负责人用户名" prop="username">
              <el-input
                clearable
                v-model.trim="addForm.username"
                placeholder="请输入用户名"
                oninput="value=value.replace(/\s*/g,'')"
                @blur="addForm.username = $event.target.value"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="负责人手机" prop="mobile">
              <el-input
                clearable
                v-model.trim="addForm.mobile"
                placeholder="请输入手机号"
                oninput="value=value.replace(/\D/g,'')"
                @blur="addForm.mobile = $event.target.value"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="法人姓名">
              <el-input
                clearable
                v-model.trim="addForm.corporateName"
                placeholder="请输入法人姓名"
                oninput="value=value.replace(/\s*/g,'')"
                @blur="addForm.corporateName = $event.target.value"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              size="small"
              label="法人身份证"
              prop="corporateIdCard"
            >
              <el-input
                clearable
                v-model.trim="addForm.corporateIdCard"
                placeholder="请输入法人身份证"
                oninput="value=value.replace(/\s*/g,'')"
                @blur="addForm.corporateIdCard = $event.target.value"
                maxlength="18"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>

      <el-dialog
        width="50%"
        title="选择地区"
        :visible.sync="innerVisible"
        append-to-body
        :close-on-click-modal="false"
      >
        <div class="mapLoc" v-if="isShowMap">
          <iframe
            :src="reqUrl"
            v-if="isShowMap"
            frameborder="0"
            class="iframe"
            seamless
            scrolling="no"
          ></iframe>
        </div>
      </el-dialog>
    </el-dialog>

    <!-- <div class="mapLoc" v-if="isShowMap">
      <iframe
              :src="reqUrl"
              v-if="isShowMap"
              frameborder="0"
              class="iframe"
              seamless
              scrolling="no"
            ></iframe>
          </div> -->
  </div>
</template>
<script>
import { reqOrgAdd, reqRegion, reqRegionLevel } from "@api/api.js";
import mixinRules from "./mixins/rules.js";
import { mapState } from "vuex";
import $ from "jquery";

export default {
  props: ["getLocationInfo", "getAddressflag"],
  mixins: [mixinRules],
  data() {
    return {
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      communityList: [], //社区
      dialogVisible: false,
      innerVisible: false,
      addForm: {
        orgName: "",
        flatType: "",
        username: "",
        mobile: "",
        parentId: "0",
        lat: "",
        lng: "",
        province: "",
        provinceCode: "",
        city: "",
        cityCode: "",
        area: "",
        areaCode: "",
        street: "",
        streetCode: "",
        address: "",
        communityCode: "", //社区
        community: "",
        nature: "", // 单位性质
        category: "",
        homeCountry: "",
        grade: "",
        telephone: "",
        corporateName: "",
        corporateIdCard: "",
        construction: "",
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      isShowMap: false,
      LocationInfo: true, //判断是否从地图选的经纬度
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    getAddressflag() {
      if (!this.dialogVisible) return;
      this.LocationInfo = true;
      this.addForm.lat = this.getLocationInfo.getLat;
      this.addForm.lng = this.getLocationInfo.getLng;
      // 先清空
      this.addForm.province = "";
      this.addForm.provinceCode = "";
      this.addForm.city = "";
      this.addForm.cityCode = "";
      this.addForm.area = "";
      this.addForm.areaCode = "";
      this.addForm.street = "";
      this.addForm.streetCode = "";
      this.addForm.community = "";
      this.addForm.communityCode = "";

      this.addForm.province = this.getLocationInfo.province;
      this.addForm.city = this.getLocationInfo.city;
      this.addForm.area = this.getLocationInfo.area;
      this.addForm.street = this.getLocationInfo.street;
      this.addForm.address =
        this.getLocationInfo.address == "我的位置"
          ? ""
          : this.getLocationInfo.address;
      // this.isShowMap = false;
      this.innerVisible = false;
      this.getRegion();
    },
    "addForm.address"(e) {
      if (this.LocationInfo) return;
      this.addrHand();
    },
    "addForm.areaCode"(e) {
      if (this.LocationInfo) return;
      this.addrHand();
    },
    // getLocationInfo: {
    //   handler(val) {
    //     this.addForm.lat = val.getLat;
    //     this.addForm.lng = val.getLng;
    //     this.addForm.province = val.province;
    //     this.addForm.city = val.city;
    //     this.addForm.area = val.area;
    //     this.addForm.street = val.street;
    //     this.addForm.address = val.address == "我的位置" ? "" : val.address;
    //     // this.isShowMap = false;
    //     this.innerVisible = false;
    //     this.getRegion();
    //   },
    //   deep: true,
    // },
  },
  methods: {
    getLongitudeLatitude() {
      // var geolocation = new BMap.Geolocation();
      //   geolocation.getCurrentPosition(function (r) {
      //     console.log(r.latitude);
      //     console.log(r.longitude);
      //     })
      //     return;
      // var location_lon = "";
      // var location_lat = ""; // 经度,纬度
      // if (navigator.geolocation) {
      //   navigator.geolocation.getCurrentPosition(function(position) {
      //     console.log(position);
      //     location_lon = position.coords.longitude;
      //     location_lat = position.coords.latitude;
      //     // console.log(location_lon, location_lat, "获取定位");
      //     this.reqUrl=`https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${location_lon},${location_lat}`
      //   });
      // }
    },
    // 查询省级行政单位
    async RegionList() {
      const res = await reqRegion();
      this.provinceList = res.data.rows;
    },
    // 根据省查询市
    async changprovince(val) {
      this.LocationInfo = false;
      this.addForm.address = "";
      this.cityList = [];
      this.addForm.city = "";
      this.addForm.cityCode = "";
      this.areaList = [];
      this.addForm.area = "";
      this.addForm.areaCode = "";
      this.streetList = [];
      this.addForm.street = "";
      this.addForm.streetCode = "";
      this.communityList = [];
      this.addForm.community = "";
      this.addForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.cityList = res.data.rows;
      this.provinceList.forEach((item) => {
        if (item.regionCode == val) {
          this.addForm.province = item.regionName;
          return;
        }
      });
    },
    // 根据市查询区
    async changcity(val) {
      this.LocationInfo = false;
      this.addForm.address = "";
      this.areaList = [];
      this.addForm.area = "";
      this.addForm.areaCode = "";
      this.streetList = [];
      this.addForm.street = "";
      this.addForm.streetCode = "";
      this.communityList = [];
      this.addForm.community = "";
      this.addForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.areaList = res.data.rows;
      this.cityList.forEach((item) => {
        if (item.regionCode == val) {
          this.addForm.city = item.regionName;
          return;
        }
      });
    },
    // 根据区查询街道
    async changarea(val) {
      this.LocationInfo = false;
      this.addForm.address = "";
      this.streetList = [];
      this.addForm.street = "";
      this.addForm.streetCode = "";
      this.communityList = [];
      this.addForm.community = "";
      this.addForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.streetList = res.data.rows;
      this.areaList.forEach((item) => {
        if (item.regionCode == val) {
          this.addForm.area = item.regionName;
          return;
        }
      });
    },
    // 街道名字赋值
    async changestreet(val) {
      this.communityList = [];
      this.addForm.community = "";
      this.addForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.communityList = res.data.rows;
      this.streetList.forEach((item) => {
        if (item.regionCode == val) {
          this.addForm.street = item.regionName;
          return;
        }
      });
    },
    // 社区名称赋值
    changecommunity(val) {
      this.communityList.forEach((item) => {
        if (item.regionCode == val) {
          this.addForm.community = item.regionName;
          return;
        }
      });
    },
    // 省市区获取
    async openMap() {
      // await  this.getLongitudeLatitude();
      this.isShowMap = true;
      this.innerVisible = true;
    },
    // 查询省级行政单位
    async getRegion() {
      const res = await reqRegion();
      // console.log(res);
      res.data.rows.forEach((item) => {
        if (item.regionName == this.addForm.province) {
          this.addForm.provinceCode = item.regionCode; //省行政码
          return;
        }
      });
      this.getRegionLevel();
    },
    // 查询省级下行政单位
    async getRegionLevel() {
      if (this.addForm.provinceCode == "") return;
      const res = await reqRegionLevel(this.addForm.provinceCode);
      this.cityList = res.data.rows;
      res.data.rows.forEach((item) => {
        if (item.regionName == this.addForm.city) {
          this.addForm.cityCode = item.regionCode; //市行政码
          return;
        }
      });
      // 特殊市辖区查不到  默认选择第一个
      if (this.addForm.cityCode == "") {
        this.addForm.city = res.data.rows[0].regionName;
        this.addForm.cityCode = res.data.rows[0].regionCode;
      }

      const res2 = await reqRegionLevel(this.addForm.cityCode);
      this.areaList = res2.data.rows;
      if (this.addForm.area == "") return; //地图中没获取到区级不走下面
      res2.data.rows.forEach((item) => {
        if (item.regionName == this.addForm.area) {
          this.addForm.areaCode = item.regionCode; //区行政码
          return;
        }
      });

      //   if (this.addForm.areaCode == "" || this.addForm.areaCode == null)
      //     return this.$modal.notifyWarning("数据异常，请联系管理员");
      const res3 = await reqRegionLevel(this.addForm.areaCode);
      this.streetList = res3.data.rows;
      if (this.addForm.street == "") return; //地图中没获取到街道不走下面
      res3.data.rows.forEach((item) => {
        if (item.regionName == this.addForm.street) {
          this.addForm.streetCode = item.regionCode; //街道行政码
          return;
        }
      });
      // console.log(this.addForm.streetCode);

      const res4 = await reqRegionLevel(this.addForm.streetCode);
      this.communityList = res4.data.rows;
      if (this.addForm.community == "") return;
      res4.data.rows.forEach((item) => {
        if (item.regionName == this.addForm.community) {
          this.addForm.communityCode = item.regionCode; //街道行政码
          return;
        }
      });
    },
    // 点击新增
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        // this.$modal.notifyWarning("请检查输入信息是否有误");
        if (!valid) return;
        let {
          parentId,
          orgName,
          lat,
          lng,
          province,
          provinceCode,
          city,
          cityCode,
          area,
          areaCode,
          street,
          streetCode,
          community,
          communityCode,
          address,
          flatType,
          nature, // 单位性质
          category,
          homeCountry,
          grade,
          telephone,
          corporateName,
          corporateIdCard,
          username,
          mobile,
          construction,
        } = this.addForm;
        if (!streetCode) return this.$modal.notifyWarning("请选择地区");
        let params = {
          parentId,
          tenantId: this.user.tenantId,
          orgName,
          lat,
          lng,
          province,
          provinceCode,
          city,
          cityCode,
          area,
          areaCode,
          street,
          streetCode,
          community,
          communityCode,
          address,
          flatType,
          nature, // 单位性质
          category,
          homeCountry,
          grade,
          telephone,
          corporateName,
          corporateIdCard,
          username,
          mobile,
          construction,
        };
        const res = await reqOrgAdd(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("新增成功");
        this.$parent.getInitDataList();
        if (username != "" && mobile != "") {
          this.$alert("新增负责人成功！登录密码默认为a123456", "", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
        }
        this.closeDialog();
      });
    },
    //地址转经纬度
    addrHand() {
      let that = this;
      // console.log(that.addForm.province+that.addForm.city+that.addForm.area+that.addForm.address);
      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: {
          key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
          address:
            that.addForm.province +
            that.addForm.city +
            that.addForm.area +
            that.addForm.street +
            that.addForm.address, //具体的地址
          output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function (json) {
          // console.log(json)
          if (json.status == 0) {
            that.addForm.lng = json.result.location.lng;
            that.addForm.lat = json.result.location.lat;
            // console.log(that.addForm.lat);
            // console.log(that.addForm.lng);
            // that.$message({
            //   message: '成功获取位置的经纬度',
            //   type: 'success'
            // })
          } else {
            // that.$message.error('获取该位置经纬度失败')
          }
        },
        error: function (err) {
          // that.$message.error('异常错误，请刷新浏览器后重试')
        },
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();
      this.dialogVisible = false;
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.communityList = [];
      this.addForm = {
        orgName: "",
        flatType: "",
        username: "",
        parentId: "0",
        lat: "",
        lng: "",
        province: "",
        provinceCode: "",
        city: "",
        cityCode: "",
        area: "",
        areaCode: "",
        street: "",
        streetCode: "",
        address: "",
        communityCode: "", //社区
        community: "",
        nature: "", // 单位性质
        category: "",
        homeCountry: "",
        grade: "",
        telephone: "",
        corporateName: "",
        corporateIdCard: "",
        mobile: "",
        construction: "",
      };
    },
    closeDialog2() {
      this.$nextTick(() => {
        this.$refs.refForm.resetFields();
      });
    },
  },
  deactivated() {
    if(this.$refs.refForm!=null){
      this.closeDialog();
    }
    this.innerVisible = false;
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

.mapLoc {
  // height: 100vh;
  // width: 100vw;
  // position: fixed;
  // z-index: 9999;
  // top: 0;
  // left: 0;

  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}

.zuobiao {
  color: @primaryTxtcolor;
}

// ::v-deep .el-textarea__inner {
//   color: #ececed !important;
// }
// 省市区/
::v-deep .el-input.is-disabled .el-input__inner {
  border-color: @primaryBorderColor !important;
}
</style>
